import { CDN_URL } from '@/utils/const/cdnUrl';

function loadCDN(scriptArr, url_key) {
  for (let i = 0; i < scriptArr.length; i++) {
    if (scriptArr[i].src === CDN_URL[url_key]) {
      return;
    }
  }
  const scriptNode = document.createElement('script');
  scriptNode.setAttribute('type', 'text/javascript');
  scriptNode.setAttribute('src', CDN_URL[url_key]);
  scriptNode.setAttribute('data-name', url_key);
  scriptNode.setAttribute('onerror', loadBackupCDN(scriptNode));
  document.body.appendChild(scriptNode);
}

// 备用CDN地址加载
function loadBackupCDN(e) {
  const target = e.getAttribute('data-name');
  if (!CDN_URL[target + '_backup']) return;
  console.warn(`${target}库的默认CDN地址加载失败，请及时变更`);
  const scriptDOM = document.createElement('script');
  scriptDOM.setAttribute('type', 'text/javascript');
  scriptDOM.setAttribute('src', CDN_URL[target + '_backup']);
  document.body.appendChild(scriptDOM);
  e.remove();
  return '';
}

export const importCDN = function(list) {
  const scripts = document.scripts;
  const scriptArr = Array.from(scripts) || [];
  list.forEach(url_key => {
    loadCDN(scriptArr, url_key);
  });
};
